package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.bean.LabelValueBean;
import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.UpmpBMchntLevelInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpBMchntLevelInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-22
 */
@Slf4j
@Service
public class UpmpBMchntLevelInfoServiceImpl extends ServiceImpl<UpmpBMchntLevelInfoMapper, UpmpBMchntLevelInfo> implements IUpmpBMchntLevelInfoService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService hisService;
    @Autowired
    private IUpmpOrganizationService organizationService;
    @Autowired
    private IUpmpSysSeqService upmpSysSeqService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;

    @Override
    public UpmpBMchntLevelInfo findOneByCode(String mchntLevel, String data_sta_01, String instId) {
        LambdaQueryWrapper<UpmpBMchntLevelInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UpmpBMchntLevelInfo::getMchntLevelCode, mchntLevel);
        queryWrapper.eq(UpmpBMchntLevelInfo::getMchntLevelStatus, data_sta_01);
        queryWrapper.eq(UpmpBMchntLevelInfo::getInstId, instId);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public IPage<UpmpBMchntLevelInfo> findByPage(QueryRequest request, UpmpBMchntLevelInfo info) {
        try {
            LambdaQueryWrapper<UpmpBMchntLevelInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(info.getInstId())) {
                queryWrapper.eq(UpmpBMchntLevelInfo::getInstId, info.getInstId());
            } else {
                //获取当前用户的法人id
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                queryWrapper.eq(UpmpBMchntLevelInfo::getInstId, user.getInstId());
            }
            if (StringUtils.isNotBlank(info.getMchntLevelCode())) {
                queryWrapper.like(UpmpBMchntLevelInfo::getMchntLevelCode, info.getMchntLevelCode());
            }
            if (StringUtils.isNotBlank(info.getMchntLevelName())) {
                queryWrapper.like(UpmpBMchntLevelInfo::getMchntLevelName, info.getMchntLevelName());
            }
            queryWrapper.orderByDesc(UpmpBMchntLevelInfo::getCreateTime);
            Page<UpmpBMchntLevelInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }

    @Override
    public Map<String, Object> getEdit(String optFlag, String instId, String id) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        UpmpBMchntLevelInfo entity = new UpmpBMchntLevelInfo();
        UpmpBMchntLevelInfo oldEntity = new UpmpBMchntLevelInfo();
        UpmpBMchntLevelInfo changeData = new UpmpBMchntLevelInfo();
        // 增加
        if ("add".equals(optFlag)) {
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            String crtOrgId = "";
            if (user.isAdmin()) {
                if (StringUtils.isEmpty(instId)) {
                    log.error("运营中心管理员新增数据必须先选择法人行！");
                    throw new RedpException("运营中心管理员新增数据必须先选择法人行！");
                } else {
                    UpmpOrganization headOrg = organizationService.getHeadOrgByCode(instId);
                    crtOrgId = (headOrg == null ? user.getOrgCode() : headOrg.getOrgCode());
                }
            } else {
                instId = (instId == null ? user.getInstId() : instId);
                crtOrgId = user.getOrgCode();
            }
            UpmpOrganization org = organizationService.getOrgByCode(crtOrgId, instId);
            entity.setId("0");
            entity.setMchntLevelCode("00000000");
            entity.setAuditStatus(BusinessContainer.status_01);
            entity.setMchntLevelStatus(BusinessContainer.agentStatus_00);
            entity.setInstId(org.getInstId());
        }
        // 修改，注销，停用，启用，详情，审批
        if ("upd".equals(optFlag) || "cancel".equals(optFlag) || "stop".equals(optFlag) ||
                "start".equals(optFlag) || "detail".equals(optFlag) || "chk".equals(optFlag)) {
            if (!"".equals(id)) {
                if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
                    BizTmp tmp = bizTmpService.getById(id);
                    if (Common.isBlank(tmp)) {
                        log.error("根据id没有找到指定临时表数据！");
                        throw new RedpException("根据id没有找到指定临时表数据！");
                    }
                    String bizdata = "";
                    if (null != tmp.getBizData1()) {
                        bizdata += tmp.getBizData1();
                    }
                    if (null != tmp.getBizData2()) {
                        bizdata += tmp.getBizData2();
                    }
                    if (null != tmp.getBizData3()) {
                        bizdata += tmp.getBizData3();
                    }
                    entity = JSON.parseObject(bizdata, UpmpBMchntLevelInfo.class);
                    String auditStatus = tmp.getAuditStatus();
                    /*if (BusinessContainer.status_41.equals(auditStatus)) {
                        oldEntity = this.getById(id);
                        List<LabelValueBean> compareBeans = CommonUtils.compareData(entity, oldEntity, UpmpBMchntLevelInfo.class);
                        //修改时对比详情数据
                        *//*result.put("checkUpdate","Y");
                        result.put("changeData",StringEscapeUtils.escapeHtml4(JSON.toJSONString(changeData, SerializerFeature.WriteMapNullValue)));*//*
                        result.put("checkUpdate", "Y");
                        result.put("compareBeans", JSON.toJSONString(compareBeans));
                    }*/
                } else {
                    entity = this.getById(id);
                }


            } else {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常！");
            }
        }

        result.put("optFlag", optFlag);
        result.put("entity", entity);
        //
        result.put("auditStatus", entity.getAuditStatus());
        result.put("mchntLevelStatus", entity.getMchntLevelStatus());
        result.put("crtOrgId", entity.getCrtOrgId());
        result.put("oprId", entity.getOprId());
        result.put("createTime", entity.getCreateTime());
        result.put("lastOprId", entity.getLastOprId());
        result.put("lastUpdateTime", entity.getLastUpdateTime());
        return result;
    }

    @Override
    public OperationResult saveData(String menuId, String oprMenuName, UpmpBMchntLevelInfo entity, String webNextUrl) throws RedpException {

        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String optFlag = entity.getOptFlag() == null ? "" : entity.getOptFlag();
        if (StringUtils.isEmpty(optFlag)) {
            return OperationResult.buildFailureResult("缺少参数optFlag!");
        }
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String instId = entity.getInstId();
        String crtOrgId = "";

        if (optFlag.equals("add") && user.isAdmin()) {
            if (StringUtils.isEmpty(instId)) {
                log.error("保存数据时请先选择法人行!");
                return OperationResult.buildFailureResult("保存数据时请先选择法人行!");
            } else {
                UpmpOrganization headOrg = organizationService.getHeadOrgByCode(instId);
                crtOrgId = (headOrg == null ? user.getOrgCode() : headOrg.getOrgCode());
            }
        } else {
            instId = (instId == null ? user.getInstId() : instId);
            crtOrgId = (entity.getCrtOrgId() == null ? user.getOrgCode() : entity.getCrtOrgId());
        }
        UpmpOrganization org = organizationService.getOrgByCode(crtOrgId, instId);

        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        UpmpBMchntLevelInfo oldEntity = null;
        if (!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            oldEntity = this.getById(entity.getId());
        }
        //新增
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            entity.setId(null);
            entity.setMchntLevelCode(generateCode(instId));
            entity.setOprId(user.getId());
            entity.setCrtOrgId(crtOrgId);
            entity.setCreateTime(lastUpddt);


            //获取审核信息
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户等级管理:新增");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //需要审核
                entity.setAuditStatus(BusinessContainer.status_01);
                entity.setMchntLevelStatus(BusinessContainer.agentStatus_00);
                //保存entity txnLimitCfgs TMP
                this.save(entity);
              /*  List<TxnLimitCfg> txnLimitCfgs = buildTxns(entity);
                for (TxnLimitCfg t : txnLimitCfgs) {
                    txnLimitCfgService.save(t);
                }*/

                bizTmpService.saveBizTmpDtl(entity, user, entity.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt,
                        menuId, oprMenuName, entity.getMchntLevelStatus(), entity.getAuditStatus(), entity.getId(), webNextUrl, "N", null, null, null, null);
            } else {
                entity.setAuditStatus(BusinessContainer.status_02);
                entity.setMchntLevelStatus(BusinessContainer.agentStatus_01);
                //保存 entity txnLimitCfgs His
                this.save(entity);
                /*
                List<TxnLimitCfg> txnLimitCfgs = buildTxns(entity);
                for (TxnLimitCfg t : txnLimitCfgs) {
                    txnLimitCfgService.save(t);
                }*/
                hisService.saveBizHisNew(entity, entity, user, entity.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt, menuId, oprMenuName, entity.getId(), null, null, null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) {
            //获取审核信息
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户等级管理:修改");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //修改的数据存入临时表，正式表仅修改状态
                UpmpBMchntLevelInfo mchntLevelInfo = this.getById(entity.getId());
                mchntLevelInfo.setAuditStatus(BusinessContainer.status_41);


                //保存 mchntLevelInfo TMP
                this.updateById(mchntLevelInfo);

                bizTmpService.saveBizTmpDtl(entity, user, entity.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        menuId, oprMenuName, BusinessContainer.agentStatus_00, mchntLevelInfo.getAuditStatus(), entity.getId(), webNextUrl, "N", null, null, null, null);

            } else {
                //保存正式表 profitconfList His
                entity.setAuditStatus(BusinessContainer.status_42);
                entity.setMchntLevelStatus(BusinessContainer.agentStatus_01);


                //保存 entity txnLimitCfgs TMP
                this.updateById(entity);
               /* //修改TxnLimitCfg
                List<TxnLimitCfg> txnLimitCfgs = updateTxns(entity);
                for (TxnLimitCfg t : txnLimitCfgs) {
                    txnLimitCfgService.save(t);
                }*/
                hisService.saveBizHisNew(entity, oldEntity, user, entity.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt, menuId, oprMenuName, entity.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {
            //商户使用过的 无法注销（作废）

            //获取审核信息
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户等级管理:注销");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                entity.setAuditStatus(BusinessContainer.status_11);

                this.updateById(entity);
                bizTmpService.saveBizTmpDtl(entity, user, entity.getInstId(), BizOprEnum.OPR_CANCEL.getType(), lastUpddt,
                        menuId, oprMenuName, BusinessContainer.agentStatus_00, entity.getAuditStatus(), entity.getId(), webNextUrl, "N", null, null, null, null);
            } else {
                entity.setAuditStatus(BusinessContainer.status_12);
                entity.setMchntLevelStatus(BusinessContainer.agentStatus_03);
                this.updateById(entity);
                hisService.saveBizHisNew(entity, oldEntity, user, entity.getInstId(), BizOprEnum.OPR_CANCEL.getType(), lastUpddt,
                        menuId, oprMenuName, entity.getId(), null, null, null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            String impStatus = entity.getMchntLevelStatus();
            String auditStatus = entity.getAuditStatus();
            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getById(entity.getId());
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定临时表数据！", result);
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }
            UpmpBMchntLevelInfo mchntLevelInfo = JSON.parseObject(bizdata, UpmpBMchntLevelInfo.class);

            String opt = entity.getOpt();
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                return OperationResult.buildFailureResult("请求参数(opt)异常!", result);
            }

            String bizOpr = "";
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType();
                    impStatus = BizDataStatusEnum.STATUS_NORMAL.getType();
                } else {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType();
                    impStatus = BizDataStatusEnum.STATUS_DRAFT.getType();
                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType();
                    impStatus = BizDataStatusEnum.STATUS_CANCELED.getType();
                } else {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType();
                }
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType();
                    impStatus = BizDataStatusEnum.STATUS_STOPED.getType();
                } else {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType();
                }
                bizOpr = BizOprEnum.OPR_STOP.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType();
                    impStatus = BizDataStatusEnum.STATUS_NORMAL.getType();
                } else {
                    impStatus = BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType();
                }
                bizOpr = BizOprEnum.OPR_USE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType();
                    impStatus = BizDataStatusEnum.STATUS_NORMAL.getType();
                } else {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType();
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }

            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                // 将临时表数据同步到正式表
                mchntLevelInfo.setAuditStatus(auditStatus);
                mchntLevelInfo.setMchntLevelStatus(impStatus);
                BeanUtils.copyProperties(mchntLevelInfo, entity);
                this.updateById(entity);
                // 审批通过将正式表更新到历史表
                hisService.saveBizHisNew(entity, oldEntity, user, entity.getInstId(), bizOpr, lastUpddt, menuId, oprMenuName, entity.getId(), null, null, null);
            } else {
                entity.setMchntLevelStatus(impStatus);
                entity.setAuditStatus(auditStatus);
                this.updateById(entity);
                impStatus = BizDataStatusEnum.STATUS_DRAFT.getType();
            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmpDtl(entity, user, entity.getInstId(), bizOpr, lastUpddt, menuId, oprMenuName, !Common.isBlank(impStatus) ? impStatus : entity.getMchntLevelStatus(), auditStatus, entity.getId(), webNextUrl, "N", null, null,null, null);
        }

        result.put("id", entity.getId());
        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }

    /**
     * 系统自动生成代理商编码：AG + 8位顺序编码
     *
     * @return
     */
    public String generateCode(String instId) {
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService, instId);
        // 代理商编码前缀：ML
        String prefix = BusinessContainer.MchntLevelInfo_PREFIX;
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum = upmpSysSeqService.updateParamValue(paramCode, "MchntLevelInfo", channelId);
        // 代理商编码
        String result = prefix + instId.substring(instId.length() - 3) + String.format("%03d", Integer.parseInt(seqNum));
        return result;
    }


    @Override
    public OperationResult chkData(String menuId, String oprMenuName, UpmpBMchntLevelInfo entity, String webNextUrl) throws RedpException {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String id = entity.getId();
        result.put("id", id);
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        String optFlag = entity.getOptFlag();
        SimpleDateFormat fmtdt = new SimpleDateFormat("yyyyMMddHHmmss");
        String lastUpddt = fmtdt.format(new Date());
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        UpmpBMchntLevelInfo oldEntity = this.getById(entity.getId());

        // 审批通过
        if ("pass".equals(optFlag)) {
            // 审批流程中
            if (BusinessContainer.status_01.equals(entity.getAuditStatus())) {
                entity.setAuditStatus(BusinessContainer.status_02); // 状态置为审批通过
                entity.setMchntLevelStatus(BusinessContainer.agentStatus_01);
                this.updateById(entity);
                hisService.saveBizHisNew(entity, oldEntity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt, menuId, oprMenuName, entity.getId(), null, null, null);
            }
            // 修改 - 审批流程中
            if (BusinessContainer.status_41.equals(entity.getAuditStatus())) {
                BizTmp tmp = bizTmpService.getById(id);
                if (Common.isBlank(tmp)) {
                    log.error("根据id没有找到指定临时表数据！");
                    return OperationResult.buildFailureResult("根据id没有找到指定临时表数据！", result);
                }
                String bizdata = "";
                if (null != tmp.getBizData1()) {
                    bizdata += tmp.getBizData1();
                }
                if (null != tmp.getBizData2()) {
                    bizdata += tmp.getBizData2();
                }
                if (null != tmp.getBizData3()) {
                    bizdata += tmp.getBizData3();
                }
                UpmpBMchntLevelInfo mchntLevelInfo = JSON.parseObject(bizdata, UpmpBMchntLevelInfo.class);
                BeanUtils.copyProperties(mchntLevelInfo, entity);
                entity.setAuditStatus(BusinessContainer.status_42);
                entity.setMchntLevelStatus(BusinessContainer.agentStatus_01);


                //保存 entity txnLimitCfgs TMP
                this.updateById(entity);
               /* //修改TxnLimitCfg
                List<TxnLimitCfg> txnLimitCfgs = updateTxns(entity);
                for (TxnLimitCfg t : txnLimitCfgs) {
                    txnLimitCfgService.save(t);
                }*/

                hisService.saveBizHisNew(entity, oldEntity, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt, menuId, oprMenuName, entity.getId(), null, null, null);

            }
            // 注销-审批流程中
            if (BusinessContainer.status_11.equals(entity.getAuditStatus())) {
                entity.setAuditStatus(BusinessContainer.status_12);
                entity.setMchntLevelStatus(BusinessContainer.agentStatus_03);
                this.updateById(entity);
                hisService.saveBizHisNew(entity, oldEntity, user, org.getInstId(), BizOprEnum.OPR_CANCEL.getType(), lastUpddt, menuId, oprMenuName, entity.getId(), null, null, null);
            }

            //处理临时表
            BizTmp tmp = bizTmpService.getById(entity.getId());
            tmp.setBizStatus(entity.getMchntLevelStatus());
            tmp.setAuditStatus(BusinessContainer.agentStatus_01);
            bizTmpService.save(tmp);
        }
        // 审批退回
        if ("back".equals(optFlag)) {
            // 状态
            String status = entity.getAuditStatus();
            entity.setMchntLevelStatus(oldEntity.getMchntLevelStatus());
            // 注销-审批流程中
            if (BusinessContainer.status_11.equals(status)) {
                entity.setAuditStatus(BusinessContainer.status_13); // 注销-审批拒绝

            }
            // 新增-审批流程中
            if (BusinessContainer.status_01.equals(status)) {
                entity.setAuditStatus(BusinessContainer.status_03); // 新增-审批拒绝

            }
            // 修改-审批流程中
            if (BusinessContainer.status_41.equals(status)) {
                entity.setAuditStatus(BusinessContainer.status_43); // 修改-审批拒绝


            }
            try {
                this.updateById(entity);
                BizTmp tmp = bizTmpService.getById(entity.getId());
                tmp.setBizStatus(entity.getMchntLevelStatus());
                tmp.setAuditStatus(BusinessContainer.agentStatus_00);
                bizTmpService.save(tmp);
                if (log.isDebugEnabled()) {
                    log.debug("保存id为：" + id + "的记录成功");
                }
            } catch (Exception e) {
                log.error("保存id为：" + id + "的记录失败", e);
                return OperationResult.buildFailureResult("处理失败！", result);
            }
        }

        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }


    @Override
    public Map<String, Object> mchntLevelSelect2List(String q, QueryRequest request) {
        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");
        LambdaQueryWrapper<UpmpBMchntLevelInfo> wrapper = new LambdaQueryWrapper<>();
        String[] param = q.split("&");
        if (param.length > 0) {
            wrapper.or(wp -> {
                wp.likeRight(UpmpBMchntLevelInfo::getMchntLevelCode, param[0])
                        .likeRight(UpmpBMchntLevelInfo::getMchntLevelName, param[0])
                        .likeRight(UpmpBMchntLevelInfo::getMchntLevelDesc, param[0]);
            });
        }
        wrapper.eq(UpmpBMchntLevelInfo::getMchntLevelStatus, BusinessContainer.data_sta_01);
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        if (user.isAdmin() && param.length > 1) {
            wrapper.eq(UpmpBMchntLevelInfo::getInstId, param[1]);
        } else {
            wrapper.eq(UpmpBMchntLevelInfo::getInstId, user.getInstId());
        }
        Page<UpmpBMchntLevelInfo> page = new Page<>();
        SortUtil.handlePageSort(request, page, true);
        Page<UpmpBMchntLevelInfo> page1 = this.page(page, wrapper);
        List<UpmpBMchntLevelInfo> listx = page1.getRecords();
        Map<String, Object> maps = new HashMap<String, Object>();
        Map<String, String> map = new HashMap<String, String>();
        List<Object> list = new ArrayList<Object>();
        for (int i = 0; i < listx.size(); i++) {
            UpmpBMchntLevelInfo ind = listx.get(i);
            map = new HashMap<String, String>();
            map.put("id", ind.getMchntLevelCode());
            map.put("name", ind.getMchntLevelName());
            map.put("desc", ind.getMchntLevelDesc());
            list.add(map);
        }
        maps.put("results", list);
        maps.put("more", false);
        return maps;
    }

    @Override
    @Transactional
    public void delete(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.baseMapper.deleteBatchIds(list);
    }

    @Override
    public List<Map> getMerLevelInfos(String instId) {
        LambdaQueryWrapper<UpmpBMchntLevelInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UpmpBMchntLevelInfo::getInstId, instId);
        wrapper.eq(UpmpBMchntLevelInfo::getMchntLevelStatus, "01");
        List<UpmpBMchntLevelInfo> mchntLevelInfos = this.list(wrapper);
        List<Map> merchantLevelInfos = new ArrayList<>();
        mchntLevelInfos.forEach((e) -> {
            Map map = new HashMap();
            map.put("MCHNTLEVEL_INF", e.getMchntLevelCode() + "-" + e.getMchntLevelName());
            merchantLevelInfos.add(map);
        });
        return merchantLevelInfos;
    }

    @Override
    public UpmpBMchntLevelInfo getMchntLevelInfo(String instId, String limit_inst) {
        LambdaQueryWrapper<UpmpBMchntLevelInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UpmpBMchntLevelInfo::getInstId, instId).eq(UpmpBMchntLevelInfo::getMchntLevelCode, limit_inst);
        return baseMapper.selectOne(wrapper);
    }
}
